package com.ssy.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ssy.common.Constant;
import com.ssy.common.utils.PageResult;
import com.ssy.common.utils.Result;
import com.ssy.common.utils.TreeNode;
import com.ssy.common.utils.TreeNodeBuilder;
import com.ssy.system.mapper.PermissionMapper;
import com.ssy.system.mapper.RoleMapper;
import com.ssy.system.pojo.Permission;
import com.ssy.system.service.IPermissionService;
import com.ssy.system.vo.PermissionVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.function.Consumer;

/**
 * @author ssy
 */
@Service
public class PermissionServiceImpl extends ServiceImpl<PermissionMapper, Permission> implements IPermissionService {

    @Autowired
    private PermissionMapper permissionMapper;

    @Autowired
    private RoleMapper roleMapper;


    /**
     * 超级管理员的权限菜单
     *
     * @param permissionVo
     * @return
     */
    @SuppressWarnings("unchecked")
    @Override
    public List<Permission> queryAllPermissionForList(PermissionVo permissionVo) {

        List<Permission> permissionList = this.permissionMapper.selectList(new LambdaQueryWrapper<Permission>()
                .eq(permissionVo.getType() != null, Permission::getType, permissionVo.getType())
                .eq(permissionVo.getAvailable() != null, Permission::getAvailable, permissionVo.getAvailable())
                .eq(StringUtils.hasText(permissionVo.getTitle()), Permission::getTitle, permissionVo.getTitle())
                .orderByAsc(Permission::getOrdernum));
        return permissionList;
    }

    /**
     * 普通管理员的权限菜单
     *
     * @param permissionVo
     * @return
     */
    @Override
    public List<Permission> queryPermissionBuUserIdForList(PermissionVo permissionVo, Integer id) {
        //根据id查询角色ID
        List<Integer> roleIds = this.roleMapper.selectRoleIdsByUserId(id);
        if (roleIds == null || roleIds.size() == 0) {
            return null;
        } else {
            List<Integer> permissionIds = this.permissionMapper.queryPermissionIdsByRoleIds(roleIds);
            if (permissionIds == null || permissionIds.size() == 0) {
                return null;
            } else {
                List<Permission> permissionList = this.permissionMapper.selectList(new LambdaQueryWrapper<Permission>()
                        .eq(Permission::getAvailable, Constant.AVAILABLE_TRUE)
                        .eq(Permission::getType, Constant.TYPE_MENU)
                        .in(Permission::getId, permissionIds)
                        .orderByAsc(Permission::getOrdernum));
                return permissionList;
            }
        }

    }

    @Override
    public PageResult loadAllpermission(PermissionVo permissionVo) {
        Page<Permission> page = new Page<>(permissionVo.getPage(), permissionVo.getLimit());
        QueryWrapper<Permission> qw = new QueryWrapper<>();

        qw.eq(StringUtils.hasText(permissionVo.getType()), "type", permissionVo.getType());
        qw.eq(permissionVo.getAvailable() != null, "available", permissionVo.getAvailable());
        qw.like(StringUtils.hasText(permissionVo.getPercode()), "percode", permissionVo.getPercode());
        qw.like(StringUtils.hasText(permissionVo.getTitle()), "title", permissionVo.getTitle());
        qw.and(permissionVo.getId() != null, new Consumer<QueryWrapper<Permission>>() {
            @Override
            public void accept(QueryWrapper<Permission> t) {
                t.eq(permissionVo.getId() != null, "id", permissionVo.getId())
                        .or()
                        .eq(permissionVo.getId() != null, "pid", permissionVo.getId());
            }
        });
        qw.orderByAsc("ordernum");

        IPage<Permission> permissionIPage = permissionMapper.selectPage(page, qw);
        return new PageResult(permissionIPage.getTotal(), permissionIPage.getRecords());
    }

    @Override
    public Integer selectMaxOrderNum() {
        return this.permissionMapper.selectMaxOrderNum();
    }

    @Override
    public int insertMenu(Permission permission) {
        return this.permissionMapper.insert(permission);
    }

    @Override
    public int updateMenuById(Permission permission) {
        if (permission.getId() == null) {
            return 0;
        }
        return this.permissionMapper.updateById(permission);
    }

    @Override
    public int deleteMenuById(Integer id) {
        if (id < 0 || id == null) {
            return 0;
        }
        return this.permissionMapper.deleteById(id);
    }

    @Override
    public int checkCurrentMenuHasChild(Integer id) {
        List<Permission> permissions = this.permissionMapper.selectList(new LambdaQueryWrapper<Permission>()
                .eq(Permission::getPid, id));
        return permissions.size();
    }

    @Override
    public int insertPermission(Permission permission) {
        return this.permissionMapper.insert(permission);
    }

    @Override
    public int updatePermissionById(Permission permission) {
        return this.permissionMapper.updateById(permission);
    }

    @Override
    public int deletePermissionById(Integer id) {
        return this.permissionMapper.deleteById(id);
    }

    @Override
    public List<String> queryPermissionByUserId(Integer userId) {
        List<Integer> roleIds = this.roleMapper.selectRoleIdsByUserId(userId);
        if (roleIds == null || roleIds.size() == 0) {
            return null;
        } else {
            List<Integer> permissionIds = this.permissionMapper.queryPermissionIdsByRoleIds(roleIds);
            if (permissionIds == null || permissionIds.size() == 0) {
                return null;
            } else {
                List<Permission> permissions = this.permissionMapper.selectList(new LambdaQueryWrapper<Permission>()
                        .eq(Permission::getAvailable, Constant.AVAILABLE_TRUE)
                        .eq(Permission::getType, Constant.TYPE_PERMISSION)
                        .in(Permission::getId, permissionIds));

                //根据用户ID查询权限
                ArrayList<String> permissionLsit = new ArrayList<>();
                for (Permission permission : permissions) {
                    permissionLsit.add(permission.getPercode());
                }
                return permissionLsit;
            }
        }

    }

    @Override
    public Result queryRolePermissionByRoleId(Integer roleId) {
        //查询可用的菜单
        QueryWrapper<Permission> qw = new QueryWrapper<>();
        qw.eq("available", Constant.AVAILABLE_TRUE);
        List<Permission> permissions = this.permissionMapper.selectList(qw);

        // 根据角色ID查询当前角色拥有的权限ID集合
        List<Integer> permissionIds = this.permissionMapper.queryPermissionIdsByRoleId(roleId);
        List<Permission> currRolePermission = null;

        // 根据角色ID 查询当前角色拥有的权限集合
        if (permissionIds == null || permissionIds.size() == 0) {
            currRolePermission = new ArrayList<Permission>();
        } else {
            qw.in("id", permissionIds);
            currRolePermission = this.permissionMapper.selectList(qw);
        }

        List<TreeNode> treeNodes = new ArrayList<>();
        for (Permission p1 : permissions) {
            String chechArr = "0";
            for (Permission p2 : currRolePermission) {
                if (p1.getId() == p2.getId()) {
                    chechArr = "1";
                    break;
                }
            }
            treeNodes.add(new TreeNode(p1.getId(), p1.getPid(), p1.getTitle(), chechArr));
        }
        List<TreeNode> build = TreeNodeBuilder.build(treeNodes, 0);
        return new Result(build);
    }
}
